package chatserver;
import java.io.*;
import java.util.*;
import java.net.*;

/**
 * 
 * Present TCP socket server
 *
 */
public class ChatServer
{
	private static Vector<Chatter> clients=new Vector<Chatter>();	//clients sockets
	private static Vector<ChatRoom> chatRooms=new Vector<ChatRoom>();
	private ServerThread serverThread=new ServerThread(clients,chatRooms);	//thread to handle clients
	private static int port = 4000;	//server port
	private boolean stop=false;	//stop flag of server
	public static void main(String args[])
	{
	/*	if(args.length<=0)
		{
			System.out.println("Command port");
			System.exit(0);
		}*/
		//init server
		//final ChatServer tcpBTPServer=new ChatServer(Integer.parseInt(args[0]));
                final ChatServer chatServer=new ChatServer(port);
		//Add shutdown hook for polite killing
		Runtime.getRuntime().addShutdownHook(new Thread() {
		      public void run() {
		        // In real life this might close a Connection or something.
		    	  chatServer.stopServer();	//inform that we want to stop the server
		    	  while(!chatServer.isStop())	//make sure the server is stopped
		    	  {
		    		  try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		    	  }
		      }
	    });		
            //TODO init default room here
            for(int i=0;i<10;i++)
            {
                if(i<5)
                {
                    ChatRoom chatRoom=new ChatRoom("Room"+i,false);
                    chatRooms.add(chatRoom);
                }else
                {
                     ChatRoom chatRoom=new ChatRoom("Room"+i,true);
                     chatRooms.add(chatRoom);
                }
            }

            chatServer.runServer();	//run the server
	}
	/**
	 * 
	 * @return true if server is truly stop
	 */
	public boolean isStop()
	{
		//Check server thread
		if(serverThread==null)
			return true;
		return serverThread.isStop();
	}
	public void stopServer()
	{
		stop=true;	//mark that we stop
		serverThread.end();	//inform server thread to stop
	}
	/**
	 * 
	 * @param port port on which server run
	 */
	public ChatServer(int port)
	{
 
		this.port=port;
	}

	/**
	 * Start server and accept connections
	 */
	public void runServer()
	{
		ServerSocket serverSocket = null;	//server socket
		Socket clientSocket = null;	//client socket
		stop=false;
		serverThread.start();	//start this thread for client processing
		try 
		{
			// Creates a ServerSocket on the specified port.
			serverSocket = new ServerSocket(port);		//start hosting
                        System.out.println("Server started!");

			while (!stop)		//While we are not stop
			{
				clientSocket = serverSocket.accept();	//accept connections
				synchronized(this.clients)
				{
					this.clients.add(new Chatter(clientSocket,""));	//pass it to server thread to handle
				}
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		// Closes the Server & Connections.
		finally
		{
			try
			{
				System.out.println("\n Closing server connection...\n");
				serverSocket.close();
			}
			catch(IOException e)
			{
				System.out.println("Unable to disconnect!");
				System.exit(1);
			}
		}
	}
}